package com.yanyuan.algorithm.search;

/**
 * @author: yanyuan
 * @Date: 2020/12/22 09:10
 * @Description:
 */
public class ArraySearch {

    public static int[] sortArr = new int[]{2,3,4,5,5,5,6,8};

    public static int findVal = 5;

    public static void main(String[] args) {
        int count = countNum(sortArr, findVal);
        System.out.println("count: " + count);
    }

    /**
     * 二分查找（有序數組）
     * @param sortArr
     * @param findVal
     * @return
     */
    public static int countNum(int[] sortArr, Integer findVal){
        int loopCount = 0;
        int count = 0;
        int start = 0;
        int end = sortArr.length - 1;
        int mid = 0;
        while (start < end){

            loopCount++;


            mid = (start + end) /2;

            if(sortArr[mid] > findVal){
                end = mid;
            }else {
                if(sortArr[mid] < findVal){
                    start = mid;
                }else {
                    count++;
                    while (sortArr[mid - 1] == sortArr[mid]){
                        loopCount++;
                        mid = mid - 1;
                    }
                    while (sortArr[mid] == sortArr[mid + 1]){
                        loopCount++;
                        mid = mid + 1;
                        count++;
                    }
                    return count;
                }
            }
        }
        System.out.println("循環次數：" + loopCount);
        return count;
    }
}
